package exp3;

import java.util.ArrayList;

/**
 * Created by 蜡笔小新丶 on 2017/11/6.
 */
public class FibonacciList {

    private int[] FibonacciList;

    public void Fibonacci(int n) {
        FibonacciList = new int[n];
        FibonacciList[0] = 0;
        FibonacciList[1] = 1;
        for (int i = 2; i < n; i++) {
            FibonacciList[i] = FibonacciList[i - 1] + FibonacciList[i - 2];
        }
    }

    public int FibonacciSearch(int key, ArrayList data, int n) {
        Fibonacci(n);
        int low, high, mid, i, k;
        low = 1;
        high = n;
        k = 0;
        //找到在斐波那契数列中对应的位置。如需要查询的数组长度为10，则在斐波那契数列的6和7之间，则      //k=7；
        while (n > this.FibonacciList[k] - 1) {
            k++;
        }
        //由于Fibonacci[7]=13，于是11和12都为空，避免出现查询空值，因此将其复制为data[10];
        for (i = n; i < FibonacciList[k] - 1; i++) {
            data.add(data.get(n));
        }
        while (low <= high) {
            mid = low + FibonacciList[k - 1] - 1;
            if (key < (int)data.get(mid)) {
                high = mid - 1;
                k--;
            } else if (key > (int)data.get(mid)) {
                low = mid + 1;
                k = k - 2;
            } else {
                if (mid <= n) {
                    return mid;
                } else {
                    return n;
                }
            }
        }
        return 0;
    }
}
